<template>
	<view>
		<app-header color="#fff" :title="headerTitle" />
		<view class="form comm-container">
			<view class="box" v-if="dizhiType=='1' ">
				<uni-forms ref="form" :modelValue="formData" :rules="rules">
					<uni-forms-item label="收货姓名" name="name">
						<input class="inp" type="text" v-model="formData.name" placeholder="请输入收货姓名" />
					</uni-forms-item>
					<uni-forms-item label="联系电话" name="phone">
						<input class="inp" type="text" v-model="formData.phone" placeholder="请输入联系电话" />
					</uni-forms-item>
					<uni-forms-item label="地区" name="province">
						<view @click="linkpopUp" style="display: flex;align-items: center;height: 100%;">
							<template v-if="!formData.province">
								<text style="flex: 24;">请选择地区</text>
							</template>
							<template v-else>
								<text
									style="flex: 24;">{{formData.province}}-{{formData.city}}-{{formData.county}}</text>
							</template>
							<uni-icons type="right" size="20"></uni-icons>
						</view>
					</uni-forms-item>
					<uni-forms-item label="详细地址" name="addressDetail">
						<input class="inp" type="text" v-model="formData.addressDetail" placeholder="请输入详细地址" />
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="box" v-else>
				<uni-forms ref="form" :modelValue="formData" :rules="rules">
					<uni-forms-item label="收货姓名" name="name">
						<input class="inp" type="text" v-model="formData.name" placeholder="请输入收货姓名" />
					</uni-forms-item>
					<uni-forms-item label="联系电话" name="phone">
						<input class="inp" type="text" v-model="formData.phone" placeholder="请输入联系电话" />
					</uni-forms-item>
					<uni-forms-item label="国家" name="cityname">
						<picker mode="selector" :range="options" range-key="name" @change="handleChange">
							<view class="picker">
								{{ selectedOption || '请选择' }}
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item label="详细地址" name="addressDetail">
						<input class="inp" type="text" v-model="formData.addressDetail" placeholder="请输入详细地址" />
					</uni-forms-item>
					<uni-forms-item>
						<u-button text="解析地址" size="normal" type="success" plain @click="handlejxdz()"></u-button>
					</uni-forms-item>
					<uni-forms-item label="城市" name="city">
						<input class="inp" type="text" v-model="formData.city" readonly />
					</uni-forms-item>
					<uni-forms-item label="邮政编码" name="postCode">
						<input class="inp" type="text" v-model="formData.postCode" placeholder="请输入邮政编码" />
					</uni-forms-item>
				</uni-forms>
			</view>
		</view>
		<view class="footer-btn">
			<u-button @click="addressConfirm" type="success" shape="circle" text="保存" style="width: 100%;"
				color="#2979FF"></u-button>
		</view>
		<u-toast ref="uToast"></u-toast>
		<uv-picker :columns="addressList" @change="change" ref="Picker" keyName="name" @confirm="Confirm" />
	</view>
</template>

<script>
	import AppHeader from "@/subpages/components/header.vue"
	import {
		putAddressDetail,
		addAddressList,
		getAddressDetail,
		getInternationalAddress
	} from "@/api/logistics.js";
	export default {
		components: {
			AppHeader
		},
		data() {
			return {
				headerTitle: "地址管理",
				dizhiType: "",
				ColumnsOptions: [],
				provinces: [],
				citys: [],
				areas: [],
				options: [{
						value: 'CN',
						name: '中国',
					},
					{
						value: 'ID',
						name: '印度尼西亚',
					},
					{
						value: 'PT',
						name: '葡萄牙',
					},
					{
						value: 'DK',
						name: '丹麦',
					},
					{
						value: 'LU',
						name: '卢森堡',
					},
					{
						value: 'HR',
						name: '克罗地亚',
					},
					{
						value: 'UA',
						name: '乌克兰',
					},
					{
						value: 'HU',
						name: '匈牙利',
					},
					{
						value: 'US',
						name: '美国',
					},
					{
						value: 'UY',
						name: '乌拉圭',
					},
					{
						value: 'IN',
						name: '印度',
					},
					{
						value: 'MX',
						name: '墨西哥',
					},
					{
						value: 'IT',
						name: '意大利',
					},
					{
						value: 'MY',
						name: '马来西亚',
					},
					{
						value: 'ES',
						name: '西班牙',
					},
					{
						value: 'AR',
						name: '阿根廷',
					},
					{
						value: 'BR',
						name: '巴西',
					},
					{
						value: 'CL',
						name: '智利',
					},
					{
						value: 'CO',
						name: '哥伦比亚',
					},
					{
						value: 'PE',
						name: '秘鲁',
					},
				],
				selectedOption: '',
				query: {
					parentld: 0
				},
				pickerValue: [0, 0, 0],
				defaultValue: [10000001, 10000035, 10000404],
				index: 0,
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入收货姓名',
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号',
						}, {
							format: 'phone',
							errorMessage: '请输入正确的手机号码',
						}]
					},
					province: {
						rules: [{
							required: true,
							errorMessage: '请输入地区',
						}]
					},
					addressDetail: {
						rules: [{
							required: true,
							errorMessage: '请输入地址',
						}]
					},
					postCode: {
						rules: [{
							required: true,
							errorMessage: '请输入邮政编码',
						}]
					}
				},
				formData: {
					name: "",
					phone: "",
					country: "",
					countryCode: "",
					province: "",
					cityname: "",
					city: "",
					county: "",
					addressDetail: "",
					postCode: "",
					isGn: ""
				}
			}
		},
		async onLoad(options) {
			this.dizhiType = options.dz
			console.log(options.dz, "dihzi ")
			if (options.id) {
				this.formData.id = options.id;
				const {
					data
				} = await getAddressDetail(this.formData.id);
				this.formData.name = data.name;
				this.formData.phone = data.phone;
				this.formData.province = data.province;
				this.formData.city = data.city;
				this.formData.county = data.county;
				this.formData.addressDetail = data.addressDetail;
				this.formData.isGn = data.isGn;
				this.formData.countryCode = data.countryCode;
				this.formData.country = data.countryCode;
				this.formData.userId = data.userId;
				this.formData.postCode = data.postCode;
				this.formData.cityname = data.countryCode;
				const selectedCountry = this.options.find(option => option.value === this.formData.countryCode);
				if (selectedCountry) {
					this.selectedOption = selectedCountry.name;
				}


				console.log(data, "data")

			}
		},
		mounted() {
			this.getData();
		},
		computed: {
			addressList() {
				return [this.provinces, this.citys, this.areas];
			}
		},
		methods: {
			// 获取寄件人地区
			handlejxdz() {
				getInternationalAddress({
					countryCode: this.formData.countryCode,
					address: this.formData.addressDetail,
					language: 'en'
				}).then(res => {
					this.formData.postCode = res.data.data.result.postCode
					this.formData.city = res.data.data.result.city
				})
			},
			handleChange(e) {
				const index = e.detail.value;
				this.selectedOption = this.options[index].name;
				this.formData.countryCode = this.options[index].value
			},
			async getData() {
				this.$store.dispatch("fetchCityList").then((cities) => {
					this.provinces = cities;
					this.handlePickValueDefault();
				});
			},
			handlePickValueDefault() {
				this.pickerValue[0] = this.provinces.findIndex(item => Number(item.id) === this.defaultValue[0]);
				this.citys = this.provinces[this.pickerValue[0]]?.children || [];
				this.pickerValue[1] = this.citys.findIndex(item => Number(item.id) === this.defaultValue[1]);
				this.areas = this.citys[this.pickerValue[1]]?.children || [];
				this.pickerValue[2] = this.areas.findIndex(item => Number(item.id) === this.defaultValue[2]);
				this.$nextTick(() => {
					this.$refs.Picker.setIndexs([this.pickerValue[0], this.pickerValue[1], this.pickerValue[2]],
						true);
				})
			},
			change(e) {
				const {
					columnIndex,
					index,
					indexs
				} = e
				// 改变了省
				if (columnIndex === 0) {
					this.citys = this.provinces[index]?.children || []
					this.areas = this.citys[0]?.children || []
					this.$refs.Picker.setIndexs([index, 0, 0], true)
				} else if (columnIndex === 1) {
					this.areas = this.citys[index]?.children || []
					this.$refs.Picker.setIndexs(indexs, true)
				}
			},
			linkpopUp() {
				this.$refs.Picker.open();
			},
			Confirm(e) {
				this.formData.province = e.value[0].name;
				this.formData.city = e.value[1].name;
				this.formData.county = e.value[2].name;
				this.defaultValue = [e.value[0].id, e.value[1].id, e.value[2].id];
			},
			succesFunction(data) {
				if (data.code == 200) {
					this.$refs.uToast.show({
						type: "success",
						message: data.msg,
						position: "center",
					});
					setTimeout(() => {
						uni.redirectTo({
							url: `/subpages/views/address/list?dz=${this.dizhiType}`
						})
					}, 1000)
				}
			},
			addressConfirm() {
				if (this.dizhiType == '1') {
					this.$refs.form.validate().then(res => {
						if (this.formData.id) {
							putAddressDetail(this.formData).then(res => {
								this.succesFunction(res)
							})
							return
						}

						this.formData.country = "中国";
						this.formData.countryCode = "CN"
						this.formData.postCode = ""
						this.formData.isGn = "1"
						addAddressList(this.formData).then(res => {
							this.succesFunction(res)
						})
					}).catch(err => {
						console.log('表单错误信息：', err);
					})
				} else {
					this.$refs.form.validate().then(res => {


						this.formData.country = this.selectedOption;
						this.formData.countryCode = this.formData.countryCode
						if (this.formData.id) {
							putAddressDetail(this.formData).then(res => {
								this.succesFunction(res)
							})
							return
						}
						this.formData.isGn = "2"
						addAddressList(this.formData).then(res => {
							this.succesFunction(res)
						})
					}).catch(err => {
						console.log('表单错误信息：', err);
					})

				}

			}
		}
	}
</script>

<style lang="scss" scoped>
	.picker {
		padding: 10px;
	}

	.form {
		::v-deep .uni-forms-item__label {
			font-size: 28rpx !important;
			width: 140rpx !important;
		}

		.box {
			background: #fff;
			box-shadow: 0rpx 7rpx 10rpx 1rpx rgba(0, 0, 0, 0.16);
			padding: 20rpx;
			border-radius: 20rpx;

			.inp {
				height: 100%;
			}
		}
	}

	.footer-btn {
		background: #fff;
		padding: 20rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		box-sizing: border-box;
		width: 100%;
	}
</style>